<#
# 使用事例：
# 在目标目录执行脚本


#>
# 脚本参数定义
param(
    [Parameter(Mandatory=$false)]
    # 使用 [switch] 类型表示布尔开关（无需值）
    [switch]$Test

    # 参数1
)

# # # 检查是否以管理员身份运行
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    # 构建重新启动脚本的参数
    $arguments = "-File `"$($MyInvocation.MyCommand.Path)`""
    $arguments += " $args"  # 传递原始参数
    
    # 启动新进程并请求管理员权限
    try {
        Start-Process powershell.exe -Verb RunAs -ArgumentList $arguments -ErrorAction Stop
        exit
    }
    catch {
        # Write-Warning "提权请求被拒绝，脚本退出。"
        Write-Warning "The privilege escalation request is denied and the script exits."
        exit 1
    }
    # 退出当前非管理员进程
    exit
}


# # 以下是需要管理员权限的脚本内容
# # Write-Host "脚本已以管理员权限运行！"
# Write-Host "The script is running with administrator privileges!"

# 你的其他代码..


# 检查是否有某命令
function which ($command) {
    Get-Command -Name $command -ErrorAction SilentlyContinue |
      Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

# 日志打印
function XWrite-Host ($FLAG,$String) {
    # $NowDateTime = $(Get-Date -f "MM-dd HH:mm:ss")
    $NowDateTime = $(Get-Date -f "HH:mm:ss")
    if ($Test) {# 传递了 --test 参数
        switch($FLAG){
        # switch -Wildcard ( $FLAG ){
            # 'Info' { 
            #     Write-Information "[$FLAG][$NowDateTime] $String ."   
            # }
            { $_ -in "Info", "INFO" } {
                # Write-Information "[$FLAG][$NowDateTime] $String ." 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor White 
            }
            'Warning' { 
                # Write-Warning -Message "[$FLAG][$NowDateTime] $String ."  
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Yellow  
            }
            { $_ -in "Debug", "DEBUG" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Blue 
            }
            { $_ -in "Error", "ERROR" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Red 
                # Write-Error -Message "[$FLAG][$NowDateTime] $String ." 
            }
            default { Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Green }
        }
    } else {
        switch($FLAG){
            { $_ -in "Info", "INFO" }  {
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor White 
            }
            { $_ -in "Error", "ERROR" } { 
                Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Red 
            }
            default { 
                # Write-Host "[$FLAG][$NowDateTime] $String ."  -ForegroundColor Green 
            }
        }
    }
}

# 下载函数

# 下载函数
# 函数 下载
function Invoke-Download
{
    param (
        [Parameter()] [string] $uri = "https://ftp.ncep.noaa.gov/data/nccf/com/hrrr/prod/hrrr.$m2/conus/hrrr.t$m21z.wrfsfcf00.grib2.idx",
        [Parameter()] [string] $outputPath = "C:\OpenGrADS-2.2\data\hrrr\test.grb2",
        [Parameter()] [int] $sleeptimer = 30,
        [Parameter()] [int] $maxTries = 3,
        [Parameter()] [int] $tries = 0
    )
    # 判断是否下载完成存在文件，存在则则不重复下载
    # $TRUE_FALSE=(Test-Path $outputPath)
    # if($TRUE_FALSE -eq "True") {
    if(Test-Path $outputPath) {
        # 文件已经存在
        XWrite-Host "INFO" "$outputPath already exists." 
    } else {
        XWrite-Host "INFO" "This is Invoke-Download(). $uri --> $outputPath" # 打印信息
        try{
            Invoke-WebRequest -Uri $uri -OutFile $outputPath;
        }
        catch [System.Net.WebException] {
            $tries++;
            XWrite-Host "INFO" "The download error is being retried`: $tries" 
            if($tries -lt $maxTries){
                Start-Sleep -Seconds $sleeptimer
                Invoke-Download -uri $uri -outputPath $outputPath -sleeptimer $sleeptimer -maxTries $maxTries -tries $tries
            } else {
                Write-Error ("Tried to download '{0}' {1}-times and failed" -f $uri, $tries);
            }
        }
    }
}

# 函数 安装 git-remote-gcrypt 
# git clone https://git.spwhitton.name/git-remote-gcrypt
function install-git-remote-gcrypt (){
    # 将 git-remote-gcrypt 里的git-remote-gcrypt 文件复制到 C:\Program Files\Git\mingw64\bin 下
    XWrite-Host "Debug" "[$CheckPath] is exist."
    # 拷贝本地文件到指定位置
    # 定义路径
    $sourceFile = Join-Path $PSScriptRoot "git-remote-gcrypt"  # 本地脚本目录下的文件
    $targetDir = "C:\Program Files\Git\mingw64\bin"           # 目标目录
    $targetPath = Join-Path $targetDir "git-remote-gcrypt"    # 目标完整路径
    
    if (-NOT (Test-Path $targetPath -PathType Leaf)) {# 验证目的文件是否存在
        if (-NOT (Test-Path $sourceFile -PathType Leaf)) {# 验证源文件是否存在
            XWrite-Host "Error" "$sourceFile is not exit" 
            exit 1
        } else {
            # 执行复制（覆盖已存在的文件）
            XWrite-Host "INFO" "$sourceFile is exit" 
            try {
                Copy-Item -Path $sourceFile -Destination $targetPath -Force -ErrorAction Stop
                XWrite-Host "INFO" "[$sourceFile] => [$targetPath] " 
            } catch {
                XWrite-Host "Error" "Failed: $_" 
                exit 1
            }
        }
    } else {
        XWrite-Host "INFO" "$targetPath is exit" 
    }
}

# 函数安装：tmux_for_windows 
# https://github.com/hongwenjun/tmux_for_windows
# 下载 https://github.com/hongwenjun/tmux_for_windows/archive/refs/heads/master.zip
# 把下载解压的tmux_for_windows-master/tmux_for_git-bash.zip在解压，将里面所以文件移动到 C:\Program Files\Git\usr\bin下
function install-git-bash-tmux() {
    # 判断是否已存在
    # 定义路径
    # $sourceFile = Join-Path $PSScriptRoot "git-remote-gcrypt"  # 本地脚本目录下的文件
    $sourceFile = Join-Path $PSScriptRoot "git-remote-gcrypt"  # 本地脚本目录下的文件
    $targetDir = "C:\Program Files\Git\usr\bin"           # 目标目录
    $targetTmuxPath = Join-Path $targetDir "tmux.exe"        # 目标完整路径
    # $githubProxyUrl = "https://github.moeyy.xyz/"  # github加速
    $githubProxyUrl = ""  # github加速
    $downloadUrl = "${githubProxyUrl}https://github.com/hongwenjun/tmux_for_windows/archive/refs/heads/master.zip"
    $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
    XWrite-Host "Debug" "targetTmuxPath = $targetTmuxPath"
    if (-NOT (Test-Path $targetTmuxPath)) { # 判断不存在
        XWrite-Host "Debug" "$targetTmuxPath is not exit." 
        # 下载 https://github.com/hongwenjun/tmux_for_windows/archive/refs/heads/master.zip
        # 解析 URL 并获取最后一段路径
        $resStr = "^$githubProxyUrl"
        $downloadUrlT = $downloadUrl -replace $resStr, '' # 去掉代理避免后面截取出错
        XWrite-Host "Debug" "lastSegment = $lastSegment"
        XWrite-Host "Debug" "downloadUrlT = $downloadUrlT"
        $uri = [System.Uri]$downloadUrlT
        $lastSegment = $uri.Segments[-1]
        XWrite-Host "Debug" "lastSegment = $lastSegment"
        # Write-Host "Press any key to continue..." -ForegroundColor Yellow
        # $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")  # 无回显，捕获所有按键
        # 智能替换文件名逻辑
        if ($lastSegment -match '^(main|master)\.zip$') {
            $saveFileNameT =  $uri.Segments[2] | ForEach-Object { $_.TrimEnd('/') } # 取域名后第2个分段路径段并去除末尾斜杠 注意加了代理后应使用倒数避免错误
            $saveFileName =  "$saveFileNameT.zip"
            XWrite-Host "Debug" "saveFileNameT = $saveFileNameT"
        } else {
            $saveFileName = $lastSegment
        }
        XWrite-Host "Debug" "saveFileName = $saveFileName"
        # 把下载解压的tmux_for_windows-master/tmux_for_git-bash.zip在解压，将里面所以文件移动到 C:\Program Files\Git\usr\bin下
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        } 
        $DownloadPath = "$DownSaveDir\$saveFileName"
        Invoke-Download $downloadUrl $DownloadPath # 下载
        # 解压
        # - 第一次解压
        $ExpandOutPath = "$DownSaveDir"
        $cmd_string="Expand-Archive  -Force -LiteralPath $DownloadPath -DestinationPath $ExpandOutPath" # 在下载保存目录解
        XWrite-Host "INFO" "--- 1 --- cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # - 第二次解压
        $ExpandsourcePath = "$DownSaveDir\$saveFileNameT-master\tmux_for_git-bash.zip"
        # $ExpandOutPath = "$DownSaveDir\$saveFileNameT-master"
        $ExpandOutPath = $ExpandsourcePath -replace '\.zip$', ''
        XWrite-Host "Debug" "ExpandOutPath = $ExpandOutPath"
        $cmd_string="Expand-Archive  -Force -LiteralPath $ExpandsourcePath -DestinationPath $ExpandOutPath" # 在下载保存目录解
        XWrite-Host "INFO" "--- 2 --- cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        #  移动
        # 移动
        $cmd_string="Move-Item -Path '$ExpandOutPath\bin\*' -Destination '$targetDir'" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        if(Test-Path "$targetTmuxPath") {
            if(Test-Path "$DownSaveDir\$saveFileNameT-master") { # 删除下载文件
                # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
                # XWrite-Host "INFO" "cmd_string = $cmd_string"
                # Invoke-Expression $cmd_string # 执行命令
                $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$saveFileNameT-master" 
                XWrite-Host "INFO" "cmd_string = $cmd_string"
                Invoke-Expression $cmd_string # 执行命令
            }
        }
    } else {
        XWrite-Host "INFO" "$targetTmuxPath is exit." 
    }
}

# 函数 主入口
function main(){
    XWrite-Host "Debug" "main()"
    $ProjectRoot = Split-Path -Path $PSScriptRoot # 获取上级父目录地址
    # 检查是否已经安装了 git-bash
    # if (which "git") {
    # if (Test-Path "C:\Program` Files\Git\cmd\git.exe"){
    $CheckPath = "C:\Program` Files\Git\mingw64\bin"
    if (Test-Path $CheckPath){
        # Git_Bash 已经安装
        # - 
        install-git-remote-gcrypt #
        # - 安装windows下Git-Bash的tmux
        install-git-bash-tmux
    } else {
        XWrite-Host "Error" "$CheckPath is not exit"
    }
    #
}

# 开始执行
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() # 创建并启动计时器 (高精度)
XWrite-Host "Debug" "stopwatch = $stopwatch"
if ($Test) {# 检查是否传递了 --test 参数
    # Write-Host "测试模式"
    Write-Host "Test Mode"
    main
} else {
    # Write-Host "普通模式"
    main
}
# 停止计时器并获取结果
$stopwatch.Stop()
$elapsedTime = $stopwatch.Elapsed
XWrite-Host "INFO" "Script execution time`: $($elapsedTime.ToString('hh\:mm\:ss\.fff')) "# 输出格式化时间（例如：00:00:05.123）

# # 显示倒计时（进阶用法）
# 1..5 | ForEach-Object {
#     # Write-Host "等待 $_ 秒..." -ForegroundColor Cyan
#     Write-Host "Wait $_ seconds ..." -ForegroundColor Cyan
#     Start-Sleep -Seconds 1
# }

# Write-Host "按任意键继续..." -ForegroundColor Yellow
Write-Host "Press any key to continue..." -ForegroundColor Yellow
$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")  # 无回显，捕获所有按键

# Read-Host "按 Enter 继续..."  # 必须按回车键